<template>
  <!-- 处方 -->
  <section>
    <el-alert type="warning" :closable="false">
      <table slot="title" width="100%" border="0">
        <tr>
          <td>过敏史：</td>
          <td>
            <div v-if="guoMinArr.length==0">否认</div>
            <div v-else>
              <span
                v-for="(item,index) in guoMinArr"
                :key="index"
                style="margin-right:10px;"
              >{{item.allergens}},{{item.allergicReaction}},{{item.allergicDegree}}</span>
            </div>
          </td>
        </tr>
      </table>
    </el-alert>
    <br />
    <div class="tab-box">
      <el-tabs v-model="tabIndex" type="card" @tab-click="onTabClick">
        <el-tab-pane
          v-for="(item,index) in tabArray"
          :key="index"
          :label="item.name"
          :name="index+''"
        >
          <tab1
            v-if="index==0"
            :guoMinArr="guoMinArr"
            :initData="item.initData"
            :dataTemplateXY="dataTemplateXY"
            :selectDrugArr="selectDrugArr"
            :cureId="cureId"
            :patientId="patientId"
            :deptId="deptId"
            :doctorId="doctorId"
            :isCopy="isCopy"
            @submit="onSubmit(item)"
            @change="onDrugChange(item)"
          ></tab1>
          <tab2
            v-else
            :guoMinArr="guoMinArr"
            :selectTemplateData="item.selectTemplateData"
            :initData="item.initData"
            :cureId="cureId"
            :patientId="patientId"
            :deptId="deptId"
            :doctorId="doctorId"
            @submit="onSubmit(item)"
            @change="onDrugChange(item)"
          ></tab2>
        </el-tab-pane>
        <el-tab-pane label="+中药处方" name="new"></el-tab-pane>
      </el-tabs>
      <div v-if="tabIndex==0" class="btn-box">
        <el-button @click="dialogSelectTemplateCF=true">选择模板</el-button>
        <el-button @click="selectDrugDrawer=true">选择药品</el-button>
        <el-button @click="onOpenCopy(1)">复制西/成药处方</el-button>
      </div>
      <div v-else class="btn-box">
        <el-button @click="selectTemplateZY=true">选择模板</el-button>
        <el-button @click="onOpenCopy(2)">复制中药处方</el-button>
      </div>
    </div>
    <dialogSelectTemplateCF
      v-model="dialogSelectTemplateCF"
      :deptId="deptId"
      :doctorId="doctorId"
      @success="onTemplateSuccess"
    ></dialogSelectTemplateCF>
    <selectDrugDrawer
      v-model="selectDrugDrawer"
      :patientId="patientId"
      :deptId="deptId"
      :channel="'MZCF'"
      :doctorId="doctorId"
      @complete="onDrugComplete"
    ></selectDrugDrawer>
    <dialogCopyCF
      v-model="dialogCopyCF"
      :patientId="patientId"
      :isCopy="isCopy"
      :cureId="cureId"
      :prescriptionType="prescriptionType"
      @copySuccess="onCopySuccess"
    ></dialogCopyCF>
    <selectTemplateZY
      v-model="selectTemplateZY"
      :patientId="patientId"
      :deptId="deptId"
      :doctorId="doctorId"
      @complete="onSuccessTemplateZY"
    ></selectTemplateZY>
  </section>
</template>
<script>
export default {
  components: {
    tab1: () => import("./_com/prescription_tab1.vue"), //西药处方
    tab2: () => import("./_com/chinaDrugCF.vue"), //中药处方
    dialogSelectTemplateCF: () => import("./_com/dialogSelectTemplateCF.vue"), //选择处方模板(西药)
    selectDrugDrawer: () => import("./_com/selectDrugDrawer.vue"), //药品分类
    dialogCopyCF: () => import("./_com/dialogCopyCF.vue"), //复制处方
    selectTemplateZY: () => import("./_com/selectTemplateZY.vue"), //中药处方模板
  },
  computed: {
    patientId() {
      return this.$store.state.doctorMZ.patientId;
    },
    doctorId() {
      return this.$store.state.doctorMZ.doctorId;
    },
    deptId() {
      return this.$store.state.doctorMZ.deptId;
    },
    cureId() {
      return this.$store.state.doctorMZ.cureId;
    },
  },
  data() {
    return {
      tabIndex: "0",
      prescriptionType: 1, //西药
      dialogCopyCF: false,
      selectDrugDrawer: false,
      dialogSelectTemplateCF: false,
      selectTemplateZY: false,
      tabArray: [],
      //选择模板的处方数据
      dataTemplateXY: [],
      //过敏数据
      guoMinArr: [],
      //初步诊断
      cureFirstVisitRecord: [],
      //选择的药品
      selectDrugArr: [],
      //是否复制处方
      isCopy: false,
      xyData: {
        curePrescriptionDrugInfos: [],
      },
    };
  },
  mounted() {
    //过敏信息
    this.getDataBi();
    this.getInitData();
  },
  methods: {
    //保存回调
    onSubmit(obj) {
      obj.isChange = false;
      let isStop = false; //是否暂停
      for (let index = 0; index < this.tabArray.length; index++) {
        const ele = this.tabArray[index];
        if (ele.isChange) {
          isStop = true;
          break;
        }
      }
      if (isStop) return;
      this.$store.commit("Set_templateSave", {
        key: "t1",
        value: false,
      });
    },
    //数据变化事件
    onDrugChange(obj) {
      this.xyData = {
        curePrescriptionDrugInfos: [],
      };
      this.xyData.curePrescriptionDrugInfos =
        obj.initData.curePrescriptionDrugInfos;
      obj.isChange = true;
      this.$store.commit("Set_templateSave", {
        key: "t1",
        value: true,
      });
    },
    //复制处方
    onCopySuccess(obj) {
      let data2Arr = [];
      if (this.prescriptionType == 1) {
        //西药
        let data = obj.curePrescriptionInfoResponses[0];
        // begin tl 2020.11.26修改
        data.prescriptionId='';
        //----end
        this.analyzeXY(data);
        this.isCopy = true;
      } else {
        //中药
        this.analyzeZY(obj.curePrescriptionInfoResponses);
      }
    },
    //选择药品
    onDrugComplete(arr) {
      let th = this;
      th.selectDrugArr = arr;
    },
    //选择中药模板
    onSuccessTemplateZY(obj) {
      let th = this;
      let index = Number.parseInt(th.tabIndex);
      let data = th.tabArray[index];
      data.selectTemplateData = obj;
    },
    //选择模板
    onTemplateSuccess(obj) {
      let th = this;
      let data1 = obj.westernMedicineDrugTemplateDTO;
      let data2Arr = obj.westernMedicineDrugTemplateMedicalAdviceDTOS;
      let arr = [];
      data2Arr.forEach((data2) => {
        let j = {
          drugName: data2.adviceName,
          sellMoney: "",
          prescriptionId: "",
          hpId: th.adminUser.hpId,
          patientId: th.patientId,
          deptId: th.adminUser.hpId,
          doctorId: th.doctorId,
          drugId: data2.medicalAdviceId,
          groupId: data2.groupNum,
          oneDose: data2.timesDosage,
          oneDoseUnit: data2.timesUnit,
          use: data2.usage,
          frequency: data2.frequency,
          useDay: data2.day,
          useTotal: data2.count,
          totalUnit: data2.unit,
          getAddress: data2.takeMedicinePlace,
          isPiece: data2.isPiece,
          id: "",
          remark: "",
          medicalDrugSale: data2.medicalDrugSale,
          inventory: data2.inventoryStatisticVO
            ? data2.inventoryStatisticVO
            : {},
        };
        arr.push(j);
      });
      th.dataTemplateXY = arr;
    },
    //获取病历
    getDataBi() {
      let th = this;
      let j = {
        cureId: th.cureId,
      };
      th.$api.getcureDynamicdetailid(j).then((res) => {
        if (res.executed) {
          // //初步诊断
          // cureFirstVisitRecord: null,
          // //病历信息
          // cureMedical: null,
          // //过敏史
          // curePatientAllergy: null,
          // //既往，个人，疫苗
          // curePatientHistory: null
          th.cureFirstVisitRecord = res.data.cureFirstVisitRecord;
          let d = res.data.curePatientAllergy;
          if (d && res.data.curePatientAllergy.length > 0) th.guoMinArr = d;
        }
      });
    },
    //点击tab
    onTabClick() {
      let th = this;
      if (th.tabIndex == "new") {
        th.tabArray.push({
          name: "中药处方" + th.tabArray.length,
          selectTemplateData: null,
          initData: null,
        });
        th.tabIndex = th.tabArray.length - 1 + "";
      }
    },
    //复制药品（dialog）
    onOpenCopy(type) {
      this.prescriptionType = type;
      this.dialogCopyCF = true;
    },
    //解析中药处方
    analyzeZY(data) {
      let th = this;
      if (data.length == 0) {
        th.tabArray.push({
          name: "中药处方",
          //选择的中药模板
          selectTemplateData: null,
          initData: null,
        });
        return;
      }
      data.forEach((d) => {
        let initData = {
          curePrescriptionDrugInfos: [],
          curePrescriptionUseInfo: d.curePrescriptionUseInfo,
        };
        if (d.curePrescriptionDrugInfos)
          d.curePrescriptionDrugInfos.forEach((obj, i) => {
            let j = {
              drugName: obj.drugName,
              sellMoney: 0,
              prescriptionId: data.prescriptionId,
              hpId: th.adminUser.hpId,
              patientId: th.patientId,
              deptId: th.adminUser.hpId,
              doctorId: th.doctorId,
              drugId: obj.drugId,
              groupId: obj.groupId ? obj.groupId : i + 1,
              oneDose: obj.oneDose,
              oneDoseUnit: obj.oneDoseUnit,
              use: obj.use,
              medicalDrugSale: obj.medicalDrugSale,
              frequency: obj.frequency,
              useDay: obj.useDay,
              useTotal: obj.useTotal,
              totalUnit: obj.totalUnit,
              getAddress: obj.getAddress,
              payStatus: obj.payStatus,
              id: obj.id,
              isPiece: obj.isPiece,
              remark: obj.remark,
              inventory: obj.inventoryStatisticVO
                ? obj.inventoryStatisticVO
                : {},
            };
            initData.curePrescriptionDrugInfos.push(j);
          });
        // let tabData=th.tabArray[Number.parseInt(th.tabIndex)];
        // console.log(tabData,th.tabIndex);
        // tabData.initData=initData;
        // let tabArr = [];
        // tabArr.push(th.tabArray[0]);
        th.tabArray.push({
          name: `中药处方${th.tabArray.length == 1 ? "" : th.tabArray.length}`,
          initData: initData,
          selectTemplateData: null,
        });
        // th.tabArray = tabArr;
      });
    },
    //解析西药处方
    analyzeXY(data) {
      let th = this;
      let arr = [];
      let list = [];
      if (data) {
        if (data.curePrescriptionDrugInfos) {
          list = [
            ...(th.xyData ? th.xyData.curePrescriptionDrugInfos : []),
            ...data.curePrescriptionDrugInfos,
          ];
          // data.curePrescriptionDrugInfos = [];
          list.forEach((obj, i) => {
            let j = {
              drugName: obj.drugName,
              sellMoney: 0,
              prescriptionId: this.xyData
                ? this.xyData.prescriptionId
                : data.prescriptionId,
              hpId: th.adminUser.hpId,
              patientId: th.patientId,
              deptId: th.adminUser.hpId,
              doctorId: th.doctorId,
              drugId: obj.drugId,
              groupId: obj.groupId ? obj.groupId : i + 1,
              oneDose: obj.oneDose,
              oneDoseUnit: obj.oneDoseUnit,
              use: obj.use,
              payStatus: obj.payStatus,
              frequency: obj.frequency,
              useDay: obj.useDay,
              useTotal: obj.useTotal,
              totalUnit: obj.totalUnit,
              getAddress: obj.getAddress,
              id: obj.id,
              status: obj.status,
              medicalDrugSale: obj.medicalDrugSale,
              isPiece: obj.isPiece,
              remark: obj.remark,
              specs: obj.specs,
              highWarning: obj.highWarning, //是否高危药品
              antibacterial: obj.antibacterial,
              inventory: obj.inventoryStatisticVO
                ? obj.inventoryStatisticVO
                : {},
            };
            arr.push(j);
          });

          let newobj = {};
          arr = arr.reduce((preVal, curVal) => {
            newobj[curVal.id] ? "" : (newobj[curVal.id] = preVal.push(curVal));
            return preVal;
          }, []);
        }
      }
      th.tabArray[0].initData = {
        curePrescriptionDrugInfos: arr,
        prescriptionId: data ? data.prescriptionId : "",
      };
    },
    //获取初始数据
    getInitData() {
      let th = this;
      //初始化
      th.tabArray = [
        {
          name: "西/成药处方",
          initData: null,
        },
      ];
      let j = {
        cureId: th.cureId,
      };
      th.$api.curePrescriptionlistcureId(j).then((res) => {
        //中药处方
        let xyData;
        let zyData = [];
        for (let i = 0; i < res.data.length; i++) {
          let d = res.data[i];
          // 西药
          if (d.prescriptionType == 1 && !xyData) {
            xyData = d;
          }
          // 中药
          if (d.prescriptionType == 2) {
            zyData.push(d);
          }
        }
        this.xyData = xyData;
        th.analyzeXY(xyData);
        th.analyzeZY(zyData);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.tab-box {
  position: relative;
  .btn-box {
    position: absolute;
    top: 0;
    right: 0;
  }
}
</style>
